package o2o.web.actions.shop;

import com.jinyou.utils.common.*;
import com.jinyouapp.common.tools.jms.model.JMSNotify;
import o2o.cache.agent.CityAgentMemory;
import o2o.cache.agent.ShopAgentRelationMemory;
import o2o.cache.shop.ShopMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.config.dao.UserDaoSql;
import o2o.config.jms.config.JMSTypeContent;
import o2o.config.jms.sender.JmsSender;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.agent.CityAgent;
import o2o.dao.PO.common.ResultInfo;
import o2o.company.model.ShopInfo;
import o2o.dao.PO.shop.ShopInfoDB;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.VO.common.FileUploadInfo;
import o2o.dao.VO.shop.ShopInfoAndGameVO;
import o2o.system.data.SYS_CONFIG_PATH;
import o2o.system.data.SYS_SETTINGS;
import o2o.web.actions.user.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLException;
import java.util.*;

//代理管理店铺
@Controller
public class AgentShopAction {

    //-----------------------------------------------------------代理（云送学校代理）
    //代理获取店铺列表
    @RequestMapping(method = RequestMethod.POST, value = "/agent/shop/list")
    @ResponseBody
    public String list(String token, Long agentId, Integer typeId, Integer isRecommend, String content, Integer page, Integer size, Integer needGoods, Integer needGoodsCount, String searchType, String order) {
        UserInfo user = null;
        if (ValidateUtil.isNotNull(token)) {
            user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        }

        if (ValidateUtil.isNotID(agentId)) {
            return AjaxResult.errorResult("请先选择代理");
        }

        boolean checkRecommend = false;
        Boolean isRecommendB = null;
        if (null != isRecommend && 0 == 1 - isRecommend) {
            checkRecommend = true;
            isRecommendB = true;
        }
        List<ShopInfo> list = ShopMan.listOfAgentId(agentId, typeId, content, checkRecommend, isRecommendB);

        if (ValidateUtil.isAbsList(list)) {
            if (ValidateUtil.isNotAbsInteger(page)) {
                page = 1;
            }
            if (ValidateUtil.isNotAbsInteger(size)) {
                size = 20;
            }

            //排序
            Collections.sort(list, new Comparator<ShopInfo>() {
                public int compare(ShopInfo arg0, ShopInfo arg1) {
                    if (null == arg0.getOrderNo() || null == arg1.getOrderNo()) {
                        return 0;
                    }
                    return arg0.getOrderNo().compareTo(arg1.getOrderNo());
                }
            });


            JYPageUtils.PageList pageList = JYPageUtils.getList(list, page, size);
            if (null != pageList && ValidateUtil.isAbsList(pageList.list)) {
                List<ShopInfoAndGameVO> voList = new ArrayList<>();
                for (int i = 0; i < pageList.list.size(); i++) {
                    if (null == pageList.list.get(i)) {
                        continue;
                    }

                    ShopInfoAndGameVO shopInfoVO = ShopListMan.getShop(user, (ShopInfo) pageList.list.get(i), true, needGoods, needGoodsCount, null);
                    if (null == shopInfoVO) {
                        continue;
                    }
                    voList.add(shopInfoVO);
                }

                if (ValidateUtil.isAbsList(voList)) {
                    return AjaxResult.successResult(pageList.totalCount, voList.size(), voList);
                }
            }
        }


        return AjaxResult.successResult(0, 0, null);
    }


    //添加店铺
    @RequestMapping(method = RequestMethod.POST, value = "/agent/shop/add")
    @ResponseBody
    public String shop_add(String token, Long agentId, ShopInfoDB info, FileUploadInfo fileUploadInfo,
                           String idCardNumber,// 店主身份证号
                           String regions,
                           String shopType) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (!User.hasShopAuth(user.getUsername(), user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        if (ValidateUtil.isNotID(agentId)) {
            return AjaxResult.errorResult("代理ID不能为空");
        }

        CityAgent cityAgent = CityAgentMemory.getInstance().getById(agentId);
        if (null == cityAgent) {
            return AjaxResult.errorResult("代理不存在");
        }

        if (!user.getUsername().equalsIgnoreCase(cityAgent.getUsername())) {
            return AjaxResult.errorResult("您不是代理，没有操作权限");
        }


        if (ValidateUtil.isNull(info.getShopName())) {
            return AjaxResult.errorResult("店铺名称不能为空");
        }
        if (ValidateUtil.isNull(info.getOwnUsername())) {
            info.setOwnUsername(DateUtils.getCurrTime() + "");
//            return AjaxResult.errorResult("店主账号不能为空");
        }

//        if (fileUploadInfo == null) {
//            return AjaxResult.errorResult("图片不能为空");
//        }

        if (null != fileUploadInfo && null != fileUploadInfo.getShopImage()) {
            //存储图片
//            String filePath = JYImageUtils.saveImage(Common.SHOPIMAGE, fileUploadInfo.getShopImage());
            String filePath = JYImageUtils.saveImage(SYS_CONFIG_PATH.SHOP_IMAGE, fileUploadInfo.getShopImage());
            if (null == filePath) {
                return AjaxResult.errorResult("存储图片失败，请稍后再试");
            }
            info.setImageUrl(filePath);
        }
        // 店铺背景图
        if (null != fileUploadInfo && (null != fileUploadInfo.getImageB() || ValidateUtil.isNotNull(fileUploadInfo.getBase64ImgB()) || ValidateUtil.isNotNull(fileUploadInfo.getImageUrlB()))) {
            //存储图片
            String filePath = null;
            if (fileUploadInfo.getImageB() != null) {
                filePath = JYImageUtils.saveImage(SYS_CONFIG_PATH.SHOP_IMAGE, fileUploadInfo.getImageB());
            } else if (ValidateUtil.isNotNull(fileUploadInfo.getBase64ImgB())) {
                filePath = JYImageUtils.saveImage(SYS_CONFIG_PATH.SHOP_IMAGE, fileUploadInfo.getBase64ImgB());
            } else {
                filePath = fileUploadInfo.getImageUrlB();
            }
            if (null == filePath) {
                return AjaxResult.errorResult("存储图片失败，请稍后再试");
            }
            info.setImageUrlB(filePath);
        }
        ResultInfo resultInfo = ShopMan.addShop(user.getUsername(), info, shopType, regions, idCardNumber);
        if (null != resultInfo && resultInfo.isSuccess()) {
            //添加店铺与代理的关系
            ShopMan.addAgentShopRelation(cityAgent, Long.parseLong(resultInfo.getObj().toString()), info.getCity(), user.getUsername());

            AjaxResult.successResult(resultInfo.getObj().toString());
        } else {
            return AjaxResult.errorResult(resultInfo.getError());
        }
        return AjaxResult.successResult();
    }


    //删除店铺
    @RequestMapping(method = RequestMethod.POST, value = "/agent/shop/delete")
    @ResponseBody
    public String shop_delete(String token, Long agentId, String shopId) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
//        if (0 != user.getUserType() - UserType.ADMIN) {
//            return AjaxResult.errorResult("您没有操作权限");
//        }
        if (ValidateUtil.isNull(shopId)) {
            return AjaxResult.errorResult("请选择要删除的店铺");
        }

        if (shopId.indexOf(",") > -1) {
            String[] shopids = shopId.split(",");
            for (int i = 0; i < shopids.length; i++) {
                if (ValidateUtil.isNotNull(shopids[i])) {
                    ShopInfo shopInfo = ShopMemory.getInstance().getShopById(Long.parseLong(shopids[i]));
                    if (null == shopInfo) {
                        return AjaxResult.errorResult("当前店铺不存在请查证");
                    }

                    if (User.notHasCityAuth(user.getUsername(), shopInfo.getCity(), user.getUserType())) {
                        return AjaxResult.errorResult("您没有访问该城市数据的权限");
                    }
                }
            }

        } else {
            ShopInfo shopInfo = ShopMemory.getInstance().getShopById(Long.parseLong(shopId));
            if (null == shopInfo) {
                return AjaxResult.errorResult("当前店铺不存在请查证");
            }

            if (User.notHasCityAuth(user.getUsername(), shopInfo.getCity(), user.getUserType())) {
                return AjaxResult.errorResult("您没有访问该城市数据的权限");
            }
        }


        //数据库删除
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.ShopInfo).append(" set delFlag=1,updateUser = '").append(user.getUsername()).append("' where id in(").append(shopId).append(")");
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("删除店铺失败，请稍后再试");
        }

        //删除代理对应的店铺
        StringBuilder sbAgent = new StringBuilder();
        sbAgent.append("update ").append(PojoTables.SHOP_AGENT_RELATION).append(" set delFlag=1,updateUser = '").append(user.getUsername())
                .append("' where agentId = ").append(agentId).append(" and shopId in (").append(shopId).append(")");
        try {
            UserDaoSql.getInstance().executeBySql(sbAgent.toString());
        } catch (SQLException e) {
            e.printStackTrace();
        }

        //删除店铺缓存
        String[] shops = shopId.split(",");
        if (null != shops && shops.length > 0) {
            for (int i = 0; i < shops.length; i++) {
                if (ValidateUtil.isNull(shops[i])) {
                    continue;
                }

                Long sId;
                try {
                    sId = Long.parseLong(shops[i]);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }

                if (ValidateUtil.isNotID(sId)) {
                    continue;
                }
                //删除店铺缓存
                ShopMemory.getInstance().delete(sId);
                try {
                    JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SHOP_INFO_DELETE).setLong01(sId);
                    JmsSender.setTopicSender(notify);
                } catch (Exception e) {
                }
                //删除代理对应的店铺关系
                ShopAgentRelationMemory.getInstance().delete(agentId, sId);
                // 数据同步
                try {
                    JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SHOP_AGENT_RELATION_DELETE).setLong01(agentId).setLong02(sId);
                    JmsSender.setTopicSender(notify);
                } catch (Exception e) {
                }
            }
        }

        return AjaxResult.successResult();
    }


    //-------------------------------------------------店铺关联商圈
    //修改店铺的商圈(代理关联)
    @RequestMapping(method = RequestMethod.POST, value = "/admin/shop/agent/relation/add")
    @ResponseBody
    public String shop_relation_add(String token, Long shopId, Long agentId, String agentIdStr) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (ValidateUtil.isNotID(shopId)) {
            return AjaxResult.errorResult("店铺ID不能为空");
        }

        ShopInfo shopInfo = ShopMemory.getInstance().getShopById(shopId);
        if (null == shopInfo) {
            return AjaxResult.errorResult("店铺不存在");
        }

        if (ValidateUtil.isNotID(agentId) && ValidateUtil.isNull(agentIdStr)) {
            return AjaxResult.errorResult("请先选择商圈");
        }

        if (ValidateUtil.isID(agentId)) { //店铺属于单独一个商圈
            //获取该店铺之前的商圈
            CityAgent oldAgent = CityAgentMemory.getInstance().getByUsername(shopInfo.getOwnUsername());
            if (null != oldAgent && 0 == agentId - oldAgent.getId()) {
                //未修改商圈
                return AjaxResult.successResult();
            }

            CityAgent cityAgent = null;
            if (ValidateUtil.isID(agentId)) {
                cityAgent = CityAgentMemory.getInstance().getById(agentId);
                if (null == cityAgent) {
                    return AjaxResult.errorResult("商圈不存在");
                }
            }

            //获取该店铺之前所属商圈
            //检查批发商个数限制
            if (null != SYS_SETTINGS.SERIES_SHOP_LIMIT_ONE_AGENT && SYS_SETTINGS.SERIES_SHOP_LIMIT_ONE_AGENT >= 0 && null != shopInfo.getIsSeriesSale() && 0 == shopInfo.getIsSeriesSale() - 1) {
                //检查该商圈下是否有批发商
                List<ShopInfo> shopList = ShopMan.listOfAgentId(agentId, 1);
                if (ValidateUtil.isAbsList(shopList) && shopList.size() >= SYS_SETTINGS.SERIES_SHOP_LIMIT_ONE_AGENT) {
                    // 获取
                    return AjaxResult.errorResult("所选商圈里，该类型的商家数量，已超出限制");
                }
            }

            ShopMan.modifyAgentShopRelation(cityAgent, shopId, user.getUsername());

        } else {
            //店铺服务多个商圈
            ShopMan.modifyShopAgentsRelation(shopId, agentIdStr, user.getUsername());
        }


        return AjaxResult.successResult();
    }

}
